<template>
    <div class="e-form">
        <BillTop :title="$route.meta.title" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs"></div>
        <div class="tabs" v-if="Object.keys(formData).length != 0">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="中标通知书"
                    name="noticeContent"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                label-width="170px"
                                :rules="rules"
                                ref="ruleForm"
                                v-if="formData.releaseState !== 1"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标编号：">
                                            <div style="display: flex">
                                                <el-input
                                                    v-model="formData.tenderApplyNo"
                                                    disabled
                                                ></el-input>
                                                <ComShowBiddingButton
                                                    :tenderId="tenderId"
                                                    mod="equipment"
                                                />
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标单位">
                                            <span>{{ formData.tenderOrgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="12">
                            <el-form-item label="拟招标项目名称：">
                                <span>{{ formData.baseInfo.projectName }}</span>
                            </el-form-item>
                        </el-col> -->
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拟招标项目名称：">
                                            <span>{{ formData.projectName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期：">
                                            <span>{{ formData.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="采购方式：">
                                            <span v-if="formData.tenderForm">{{
                                                formData.tenderForm | tenderForm(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标类型：">
                                            <span>{{ tenderClass | tenderClass(this) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="包件名称：" prop="packageName">
                                            <el-select
                                                v-model="formData.packageName"
                                                filterable
                                                placeholder="请选择"
                                                @change="selectChange($event, '包件名称')"
                                            >
                                                <el-option
                                                    v-for="item in packageNameOptions"
                                                    :key="item.dtlId"
                                                    :label="item.name"
                                                    :value="item.name"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="通知对象：" prop="noticeUser">
                                            <el-select
                                                v-model="formData.noticeUser"
                                                filterable
                                                placeholder="请选择"
                                                @change="selectChange($event, '通知对象')"
                                            >
                                                <el-option
                                                    v-for="item in noticeUserNameOptions"
                                                    :key="item.candidateId"
                                                    :label="item.candidateName"
                                                    :value="item.candidateName"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="是否中标：" prop="isBid">
                                            <el-radio v-model="formData.isBid" :label="0"
                                                >未中标</el-radio
                                            >
                                            <el-radio v-model="formData.isBid" :label="1"
                                                >已中标</el-radio
                                            >
                                            <!-- <span>{{ formData.baseInfo.isBid === 0 ? '否' : '是' }}</span> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                formData.releaseState | releaseState(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input
                                                type="textarea"
                                                :rows="2"
                                                placeholder="请输入内容"
                                                v-model="formData.remarks"
                                                style="margin-right: 110px"
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                            <el-form
                                :model="formData"
                                label-width="170px"
                                :rules="rules"
                                ref="ruleForm"
                                v-else
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标编号：">
                                            <div style="display: flex">
                                                <span>{{ formData.tenderApplyNo }}</span>
                                                <ComShowBiddingButton
                                                    :tenderId="tenderId"
                                                    mod="equipment"
                                                />
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标单位">
                                            <span>{{ formData.tenderOrgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="12">
                            <el-form-item label="拟招标项目名称：">
                                <span>{{ formData.baseInfo.projectName }}</span>
                            </el-form-item>
                        </el-col> -->
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拟招标项目名称：">
                                            <span>{{ formData.projectName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期：">
                                            <span>{{ formData.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="采购方式：">
                                            <span v-if="formData.tenderForm">{{
                                                formData.tenderForm | tenderForm(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标类型：">
                                            <span>{{ tenderClass | tenderClass(this) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="包件名称：" prop="packageName">
                                            <span>{{ formData.packageName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="通知对象：" prop="noticeUser">
                                            <span>{{ formData.noticeUser }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="是否中标：" prop="isBid">
                                            <el-radio v-model="formData.isBid" :label="0" disabled
                                                >未中标</el-radio
                                            >
                                            <el-radio v-model="formData.isBid" :label="1" disabled
                                                >已中标</el-radio
                                            >
                                            <!-- <span>{{ formData.baseInfo.isBid === 0 ? '否' : '是' }}</span> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                formData.releaseState | releaseState(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <span>{{ formData.remarks }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="noticeContentCon" class="con">
                        <div class="tabs-title" id="noticeContent">通知内容</div>
                        <div>
                            <ComQuillEditor
                                ref="ComQuillEditor"
                                v-model="content.content"
                                :disabled="formData.releaseState === 1"
                            />
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <ComAttachIndex
                            bucketName="tender"
                            :relationId="billId"
                            ref="ComAttachIndex"
                            :key="1"
                            :isView="formData.releaseState === 1"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                class="btn-blue"
                size="small"
                @click="release"
                v-if="formData.releaseState !== 1"
                >发布</el-button
            >
            <el-button
                type="primary"
                slot="reference"
                class="btn-blue"
                @click="deleteData"
                v-if="formData.releaseState !== 1"
                >删除</el-button
            >
            <el-button type="primary" class="btn-blue" @click="submit">保存</el-button>
            <el-button @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import ComPagination from '@/components/pagination/pagination.vue'
import ComShowBiddingButton from '@/pages/bidding/common/showBiddingButton.vue'
// import bidNoticeRequest from '@/api/tender/bidNotice.js'
import ComQuillEditor from '@/components/quillEditor.vue'
import ComAttachIndex from '@/components/common/attachIndex'
import equipmentProcurementRequest from '@/api/tender/equipmentProcurement.js'
import { mapState } from 'vuex'

export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {},
            test: '',
            selectData: [],
            selectTableColumnAttr: [
                {
                    label: '单据编号',
                    prop: 'billNo'
                },
                {
                    label: '拟招标项目名称',
                    prop: 'tenderName'
                },
                {
                    label: '单据日期',
                    prop: 'gmtCreate'
                },
                {
                    label: '单据机构名称',
                    prop: 'orgName'
                }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            selectDataPagination: {},
            content: {
                billId: this.$route.query.billid,
                content: '',
                gmtCreate: '',
                gmtModified: '',
                recordId: ''
            },
            tenderClass: 3,
            rules: {
                isBid: {
                    required: true,
                    message: '请选择是否中标',
                    trigger: 'change'
                },
                noticeUser: {
                    required: true,
                    message: '请选择通知对象',
                    trigger: 'change'
                },
                packageName: {
                    required: true,
                    message: '请选择包件名称',
                    trigger: 'change'
                }
            },
            noticeUserNameOptions: [],
            packageNameOptions: []
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.formData.tenderApplyId
        },
        billId () {
            return this.$route.query.billId || this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        // ComPagination,
        ComShowBiddingButton,
        ComQuillEditor,
        ComAttachIndex
    },
    async created () {
        // 查询基础信息
        await this.getData()
        // 查询通知内容
        this.noticeContentGetById()
        this.getCandidate() // 获取通知对象下拉列表
        this.getPackage() // 获取包件下拉列表
    },
    mounted () {
        // 保存所有tabName
        const arr = ['baseInfo', 'attach', 'auditHistory']
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight(arr)
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item)?.offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item)?.offsetTop
                return itemTop
            })
        })
    },
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        async release () {
            if (this.content.content === '') {
                this.clientPop('err', '必须填写通知内容才能发布')
                return
            }
            await equipmentProcurementRequest.noticeContentCreate(this.content)
            this.noticeContentGetById()
            var params = { billId: this.billId, type: '4' }
            equipmentProcurementRequest.release(params).then(() => {
                this.clientPop('suc', '发布成功')
                this.getData()
            })
        },
        selectChange (name, label) {
            if (label === '包件名称') {
                this.packageNameOptions.forEach(item => {
                    if (item.name === name) {
                        this.formData.packageId = item.dtlId
                    }
                })
                this.getCandidate()
            } else if (label === '通知对象') {
                this.noticeUserNameOptions.forEach(item => {
                    if (item.candidateName === name) {
                        this.formData.noticeUserId = item.candidateId
                    }
                })
            }
        },
        getCandidate () {
            equipmentProcurementRequest
                .noticeGetCandidate({ packageId: this.formData.packageId })
                .then(res => {
                    this.noticeUserNameOptions = res
                })
        },
        getPackage () {
            equipmentProcurementRequest
                .noticeGetPackagey({ tenderApplyId: this.tenderId })
                .then(res => {
                    this.packageNameOptions = res
                })
        },
        noticeContentGetById () {
            equipmentProcurementRequest.noticeContentGetById({ id: this.billId }).then(res => {
                if (res.data !== null) {
                    this.content = res
                }
            })
        },
        deleteData () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', this.delData)
        },
        onChangeTab (e) {
            const height = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight (arr) {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById(arr[length - 1] + 'Con')) {
                    const lastConHeight = document.getElementById(
                        arr[length - 1] + 'Con'
                    )?.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        delData () {
            equipmentProcurementRequest.noticeDelete({ id: this.billId }).then(() => {
                const callBack = () => {
                    this.$router.push({
                        path: './equipmentBiddingApplicationEdit',
                        query: {
                            billid: this.tenderId,
                            seat: 'bidWinningNotice'
                        }
                    })
                }
                this.clientPop('suc', '删除成功', callBack)
            })
        },
        async getData () {
            await equipmentProcurementRequest.noticeGetById({ id: this.billId }).then(res => {
                this.formData = res
            })
        },
        showBidding () {
            if (!this.tenderId) return // 前期需求可切换，现在不需要
            this.$notify.closeAll()
            this.$notify({
                title: '查看招标详情',
                dangerouslyUseHTMLString: true,
                message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/biddingApplicationShow?tenderId=${this.tenderId}</textarea>
                `,
                duration: 0
            })
            // this.$router.push({
            //     path: './biddingApplicationShow',
            //     query: { tenderId: this.tenderId }
            // })
        },
        submit () {
            // 基础信息验证
            this.$refs.ruleForm.validate(async valid => {
                if (!valid) {
                    this.onChangeTab({ name: 'baseInfo' })
                    return false
                }
            })
            // 通知内容验证
            if (this.content.content === '') {
                this.clientPop('err', '请填写通知内容')
                this.onChangeTab({ name: 'noticeContent' })
                return false
            }
            // 基础信息保存
            const promise1 = equipmentProcurementRequest.noticeUpdate(this.formData)
            const promise2 = equipmentProcurementRequest.noticeContentCreate(this.content)
            Promise.all([promise1, promise2]).then(() => {
                this.noticeContentGetById()
                this.clientPop('suc', '保存成功')
            })
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            this.$set(this.formData, 'applyTime', nowtime)
        },
        handleClose () {
            this.$router.push({
                path: './equipmentBiddingApplicationEdit',
                query: { billid: this.tenderId, seat: 'bidWinningNotice' }
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
